from setting import *
import redis
import json

class RedisUtils:
    def __init__(self):
        self.pool = redis.ConnectionPool(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB, decode_responses=True)
        self.r = redis.Redis(connection_pool=self.pool)

    def get(self, name: str):
        return self.r.get(name)

    def set(self, name: str, value: str, expire_by_seconds=0):
        if expire_by_seconds:
            self.r.set(name, value, ex=expire_by_seconds)
        else:
            self.r.set(name, value)

    def getDict(self, name: str):
        """ 获取value值并转换为字典 """
        str_v = self.r.get(name)
        if str_v:
            return json.loads(str_v)
        else:
            return None

    def setDict(self, name: str, value: dict, expire_by_seconds=0):
        json_str = json.dumps(value)
        if expire_by_seconds:
            self.r.set(name, json_str, ex=expire_by_seconds)
        else:
            self.r.set(name, json_str)


redis_utils = None
if SAVE_MODE.upper() == 'REDIS':
    redis_utils = RedisUtils()